package com.zhl.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 获取连接对象工具类
 */
@Component //创建bean对象
public class ConnUtils {
    //使用本地线程  装载数据库连接对象
    private ThreadLocal<Connection> t1 = new ThreadLocal<Connection>();
    //提供DataSource
    @Autowired  // 自动装载
    private DataSource dataSource;
    //获取连接对象
    public Connection getConnection(){
        try {
            //从本地线程中取出连接对象
            Connection conn = t1.get();
            if(conn == null){
                //从数据源获取对象
                conn = dataSource.getConnection();
                //存储进本地线程
                t1.set(conn);
            }
            return conn;
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }
    }
    /**
     * 解绑线程
     */
    public void remove(){

        t1.remove();
    }
}
